function config() {

}

config.prototype.init = function () {
	
	this.myCookie = new Mojo.Model.Cookie("config");
	this.preferences = this.myCookie.get();
	this.models = {};
	this.models.categories = [];
	this.models.people = [];
	this.models.stores = [];
	
	this.models.categories.push({'value': 1, 'id': "1", 'label': 'Family'});
	this.models.categories.push({'value': 2, 'id': "2", 'label': 'Friends'});
	this.models.categories.push({'value': 3, 'id': "3", 'label': 'Co-Workers'});
	this.models.categories.push({'value': 4, 'id': "4", 'label': 'Other'});
	
	if (!this.preferences) {
		// initize cookie...
		
		
	}
	
	this.db = openDatabase("shopping", "1", "Database used by the Christmas Shopping App", "1000000");
	//this.checkDB();
	
	this.loadCategories();
	//this.loadPeople();
	
	this.audioPlayer = new Audio();
	this.audioPlayer.src = Mojo.appPath + 'sounds/hohoho.mp3';
	this.audioPlayer.autoplay = false;


}

config.prototype.updateModels = function () {
	var controller = Mojo.Controller.appController.getActiveStageController().getActiveScene();
	controller.modelChanged(config.models.people);
	controller.modelChanged(config.models.categories);
}

config.prototype.loadCategoryTotals = function(callback) {
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select p.category_id, sum(p.budget) as totalBudget from people p group by p.category_id; GO;', [], 
				function(t,result) {
					var list = {};
					var numRows = result.rows.length;
					for (i = 0; i < numRows; i++) {
						var id= "cat" + result.rows.item(i)['category_id'];
						list[id] = result.rows.item(i)['totalBudget'];
					}
					try {
						callback(list);
					} catch(e) {
						config.log("category total callback" + e.message);
					}
				}, function (t,e) { config.log(e.message); });  
	        }).bind(this)
	    );
}

config.prototype.santaClick = function() {
	config.log("santa");
	this.audioPlayer.play();
}

config.prototype.loadCategories = function (callback) {
	
	return;
	//load categories...
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select * from peoplecategories; GO;', [], 
				function(t,result) {
					var list = [];
					var numRows = result.rows.length;
					for (i = 0; i < numRows; i++) {
						var id= "" + result.rows.item(i)['category_id'];
						list.push ({'id': result.rows.item(i)['category_id'], 'value': result.rows.item(i)['category_id'], 'label': result.rows.item(i)['category']});
					}
					config.models.categories = list;
					try {
						callback();
					} catch(e) {
						config.log("category callback" + e.message);
					}
				});  
	        }).bind(this)
	    );
}

config.prototype.loadPeople = function (callback) {
	//load categories...
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select p.*, (select count(*) from gifts g where g.people_id=p.people_id) as giftCount from people p; GO;', [], 
				function(t,result) {
					
					var list = [];
					var numRows = result.rows.length;
					
					for (i = 0; i < numRows; i++) {
						var item = result.rows.item(i);
						item['label'] = item['name'];
						item['value'] = item['people_id'];
						list.push (item);
					}
					
					config.models.people = list;
					try {
						callback();
					} catch(e) {
						config.log("people callback" + e.message);
					}
				});  
	        }).bind(this)
	    );
}

config.prototype.loadGifts = function (people_id, callback) {
	//load categories...
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select g.*, (select s.name from stores s where s.store_id=g.store_id) as storeName from gifts g where g.people_id=? order by must_have desc; GO;', [people_id], 
				function(t,result) {
					
					var list = [];
					var numRows = result.rows.length;
					
					for (i = 0; i < numRows; i++) {
						var item = result.rows.item(i);
						list.push (item);
					}

					try {
						callback(list);
					} catch(e) {
						config.log("gifts callback" + e.message);
					}
				});  
	        }).bind(this)
	    );
}

config.prototype.loadAllGifts = function (callback) {
	//load categories...
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select g.*, p.name as giftFor, (select s.name from stores s where s.store_id=g.store_id) as storeName from gifts g, people p where g.people_id=p.people_id order by g.must_have desc; GO;', [], 
				function(t,result) {
					
					var list = [];
					var numRows = result.rows.length;
					
					for (i = 0; i < numRows; i++) {
						var item = result.rows.item(i);
						list.push (item);
					}

					try {
						callback(list);
					} catch(e) {
						config.log("gifts callback" + e.message);
					}
				}, function(t,err) { config.log(Object.toJSON(err))});  
	        }).bind(this)
	    );
}


config.prototype.loadGiftsByStore = function (store_id, callback) {
	//load categories...
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select g.*, p.name as giftFor, (select s.name from stores s where s.store_id=g.store_id) as storeName from gifts g, people p where g.people_id=p.people_id and g.store_id=? order by g.must_have desc; GO;', [store_id], 
				function(t,result) {
					
					var list = [];
					var numRows = result.rows.length;
					
					for (i = 0; i < numRows; i++) {
						var item = result.rows.item(i);
						list.push (item);
					}

					try {
						callback(list);
					} catch(e) {
						config.log("gifts callback" + e.message);
					}
				}, function(t,err) { config.log(Object.toJSON(err))});  
	        }).bind(this)
	    );
}

config.prototype.loadStores = function (callback) {
	//load categories...
	this.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('select s.*, (select sum(g.cost) from gifts g where g.store_id=s.store_id) as budget, (select count(*) from gifts g2 where g2.store_id=s.store_id) as totalGifts, (select count(*) from gifts g3 where g3.store_id=s.store_id and g3.bought=0 and g3.must_have=1) as totalPending from stores s order by s.name; GO;', [], 
				function(t,result) {
					
					var list = [];
					var numRows = result.rows.length;
					
					for (i = 0; i < numRows; i++) {
						var item = result.rows.item(i);
						item['label'] = item['name'];
						item['value'] = item['store_id'];
						item['hasGifts'] = item['totalGifts'] > 0 || item['store_id'] == 1;
						list.push (item);
					}
					
					config.models.stores = list;
					try {
						callback(list);
					} catch(e) {
						config.log("people callback" + e.message);
					}
				}, function (t, e) { config.log(e.message); });  
	        }).bind(this)
	    );
}

config.prototype.checkDB = function() {

	this.db.transaction( 
	        (function (transaction) { 
				//transaction.executeSql('drop table if exists gifts; GO;', [], function(t,e) {config.log("gifts dropped");}, function(t,e) {config.log("drop" + e.message);}); 
	            //transaction.executeSql('drop table if exists people; GO;', [], function(t,e) {config.log("people dropped");}, function(t,e) {config.log("drop" + e.message);}); 
	            //transaction.executeSql('drop table if exists peoplecategories; GO;', [], function(t,e) {config.log("peoplecategories dropped");}, function(t,e) {config.log("drop" + e.message);}); 
	            //transaction.executeSql('drop table if exists stores; GO;', [], function(t,e) {config.log("stores dropped");}, function(t,e) {config.log("drop" + e.message);}); 
	            
				transaction.executeSql("CREATE TABLE if not exists [gifts] ([gift_id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,[name] text  NULL, [description] text NULL, [cost] numeric  NULL,[bought] integer DEFAULT '0' NULL,[need_by] integer  NULL, [must_have] integer '1', [store_id] integer  NULL, [people_id] integer NULL); GO;", [], function(t,e) {config.log("tes2t");}, function(t,e) {config.log("gifts" + e.message);});
				transaction.executeSql("CREATE TABLE if not exists [people] ([people_id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,[name] text  NULL,[budget] NUMERIC  NULL,[category_id] INTEGER  NULL); GO;", [], function(t,e) {config.log("test");}, function(t,e) {config.log("people" + e.message);});
				transaction.executeSql("CREATE TABLE if not exists [peoplecategories] ([category_id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,[category] text  NULL); GO;", [], function(t,e) {config.log("test");}, function(t,e) {"peoplecategories" + config.log(e.message);});
				transaction.executeSql("CREATE TABLE if not exists [stores] ([store_id] INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,[name] text  NULL); GO;", [], function(t,e) {config.log("test4");}, function(t,e) {"stores" + config.log(e.message);});
				transaction.executeSql("insert into peoplecategories values (1, 'Family'); GO;", [], function(t,e) {config.log("test5");}, function(t,e) {config.log(e.message+"1");});
				transaction.executeSql("insert into peoplecategories values (2, 'Friends'); GO;", [], function(t,e) {config.log("test5");}, function(t,e) {config.log(e.message+"2");});
				transaction.executeSql("insert into peoplecategories values (3, 'Co-Workers'); GO;", [], function(t,e) {config.log("test5");}, function(t,e) {config.log(e.message)+"3";});
				transaction.executeSql("insert into peoplecategories values (4, 'Other'); GO;", [], function(t,e) {config.log("test5");}, function(t,e) {config.log(e.message)+"4";});
				//transaction.executeSql("insert into people values (1, 'khurram khan', 100.00, 1); GO;", [], function(t,e) {config.log("test6");}, function(t,e) {config.log(e.message)+"4";}); 
				//transaction.executeSql("insert into stores values (1, 'Best Buy'); GO;", [], function(t,e) {config.log("test7");}, function(t,e) {config.log(e.message)+"4";});
				transaction.executeSql("insert into stores values (1, 'Unspecified'); GO;", [], function(t,e) {config.log("test8");}, function(t,e) {config.log(e.message)+"4";});
	        }).bind(this) 
	    );
}

config.prototype.savePreferences = function() {
	this.myCookie.put(this.preferences);
}

config.prototype.log = function(text) {
	//$('logger').update(text + "<BR>" + $('logger').innerHTML);
}

config.prototype.setupViewMenu = function(controller, toggleCmd) {
	this.viewMenuModel = {
		
		items: [{
			toggleCmd: toggleCmd,
			items: [{
				label: "People",
				command: 'view-people',
				width: 106
			}, {
				label: "Gifts",
				command: 'view-gifts',
				width: 106
			}, {
				label: "Stores",
				command: 'view-stores',
				width: 106
			}]
		}
		    ]
	}
	controller.setupWidget(Mojo.Menu.viewMenu, {}, this.viewMenuModel);
	controller.pushCommander(this);
	this.controller = controller;
}

config.prototype.handleCommand = function(event)
{
	if (event.type == Mojo.Event.command) {
		switch (event.command) {
			case "view-people":
				this.controller.stageController.swapScene("Main");
				break;
				
			case "view-gifts":
				this.controller.stageController.swapScene("GiftsList");
				break;
				
			case "view-stores":
				this.controller.stageController.swapScene("StoreList");
				break;
		}
	}
}

function DBHelper(db) {

}

DBHelper.prototype.insertPerson = function (data, success, failure)
{
	config.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('insert into people (name, category_id, budget) values (?,?,?); GO;', [data.name, data.category, data.budget], 
				function(tx,rs) { try {success(rs);} catch(e) {config.log(e.message)} }, function(tx,err) { try {failure(rs);} catch(e) {config.log(e.message)} });  
	        }).bind(this)
	    );
	config.log("out insert");
}

DBHelper.prototype.deletePerson = function (people_id, success, failure)
{
	var params = [people_id];
	var sql2 = "delete from gifts where people_id=?";
	this.query(sql2, params);
	
	var sql = "delete from people where people_id=?";
	
	this.query(sql, params, success, failure);
	config.log("out delete");
}

DBHelper.prototype.deleteGift = function (gift_id, success, failure)
{
	var params = [gift_id];
		
	var sql = "delete from gifts where gift_id=?";
	
	this.query(sql, params, success, failure);
	config.log("out delete gifts");
}

DBHelper.prototype.deleteStore = function (store_id, success, failure)
{
	var params = [store_id];
		
	var sql = "delete from stores where store_id=?";
	
	this.query(sql, params, success, failure);
	config.log("out delete stores");
}

DBHelper.prototype.insertStore = function (data, success, failure)
{
	config.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('insert into stores (name) values (?); GO;', [data.name], 
				function(tx,rs) { try {success(rs);} catch(e) {config.log(e.message)} }, function(tx,err) { try {failure(rs);} catch(e) {config.log(e.message)} });  
	        }).bind(this)
	    );
	config.log("out insert");
}

DBHelper.prototype.savePerson = function (data, success, failure)
{
	config.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql('update people set name=?, category_id=?, budget=? where people_id=?; GO;', [data.name, data.category, data.budget, data.people_id], 
				function(tx,rs) { try {success(rs);} catch(e) {config.log(e.message)} }, function(tx,err) { try {failure(rs);} catch(e) {config.log(e.message)} });  
	        }).bind(this)
	    );
	config.log("out update");
}

DBHelper.prototype.saveGift = function (data, success, failure)
{
	var sql = "replace into gifts (gift_id, name, description, cost, bought, need_by, must_have, people_id, store_id) values (?,?,?,?,?,?,?,?,?)";
	var params = [data.gift_id, data.name, data.description, data.cost, data.bought, data.need_by, data.must_have, data.people_id, data.store_id];
	this.query(sql, params, success, failure);
}

DBHelper.prototype.query = function (sql, params, success, failure)
{
	config.log("in query");
	config.db.transaction( 
	        (function (transaction) { 
				transaction.executeSql(sql + '; GO;', params, function(tx,rs) { try {success(rs);} catch(e) {config.log(e.message)} }, function(tx,err) { try {config.log(err.message);failure(err);} catch(e) {config.log("FAIL: " + e.message)} });  
	        }).bind(this)
	    );
	config.log("out query");
}


var config = new config();
config.init();
var dbHelper = new DBHelper();


//config.init();